package net.alexromeo.magicapimultiuser;

/**
 * @author AlexRomeo
 * @date 2025/5/17 23:03
 * version 1.0
 * 类作用：
 * 登录拦截器
 * 用户的token过期时间。
 */

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.context.MagicUser;
import org.ssssssss.magicapi.core.exception.MagicLoginException;
import org.ssssssss.magicapi.core.interceptor.AuthorizationInterceptor;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 自定义用户名密码登录
 */

@Component
public class CustomAuthorizationInterceptor implements AuthorizationInterceptor {

    // 数据库连接
    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 登录拦截
    @Override
    public boolean requireLogin() {
        return true; // 所有接口强制要求登录
    }

    /*
     * 通过token获取用户信息
     */
    @Override
    public MagicUser getUserByToken(String token) throws MagicLoginException {
        String sql = "SELECT user_id, username, expire_time FROM magic_api_user_tokens WHERE token = ?";
        try {
            return jdbcTemplate.queryForObject(sql, (rs, rowNum) -> {
                // 检查Token是否过期
                Timestamp expireTime = rs.getTimestamp("expire_time");
                if (expireTime.before(new Timestamp(System.currentTimeMillis()))) {
                    try {
                        throw new MagicLoginException("Token已过期");
                    } catch (MagicLoginException e) {
                        throw new RuntimeException(e);
                    }
                }
                return new MagicUser(
                        rs.getString("user_id"),
                        rs.getString("username"),
                        token
                );
            }, token);
        } catch (EmptyResultDataAccessException e) {
            throw new MagicLoginException("Token无效");
        } catch (Exception e) {
            throw new MagicLoginException("Token验证失败: " + e.getMessage());
        }
    }


    // 登录
    @Override
    public MagicUser login(String username, String password) throws MagicLoginException {
        // 1. 验证用户名密码
        String userSql = "SELECT id, password FROM magic_api_users WHERE username = ?";
        try {
            User user = jdbcTemplate.queryForObject(userSql, (rs, rowNum) ->
                            new User(
                                    rs.getLong("id"),
                                    username,
                                    rs.getString("password")
                            ),
                    username
            );

            // 2. 验证密码（实际项目应使用BCrypt等加密验证）
            if (user != null && user.getPassword().equals(password)) {
                String token = UUID.randomUUID().toString();
                // 设置1天有效期
                LocalDateTime expireTime = LocalDateTime.now().plusDays(1);
                jdbcTemplate.update(
                        "INSERT INTO magic_api_user_tokens (user_id, username, token, expire_time) VALUES (?, ?, ?, ?)",
                        user.getId(),
                        username,
                        token,
                        Timestamp.valueOf(expireTime) // 存入过期时间
                );
                return new MagicUser(user.getId().toString(), username, token);
            }
        } catch (Exception e) {
            // 用户不存在等情况
        }
        throw new MagicLoginException("用户名或密码错误");
    }


    // 内部用户类
    private static class User {
        private final Long id;
        private final String username;
        private final String password;

        public User(Long id, String username, String password) {
            this.id = id;
            this.username = username;
            this.password = password;
        }

        public Long getId() {
            return id;
        }

        public String getUsername() {
            return username;
        }

        public String getPassword() {
            return password;
        }

    }
}
